import React from 'react';
import PropTypes from 'prop-types';
import routes from './routes';
import cloneDeep from 'lodash/cloneDeep';
import {getDetail, getDealersQuickly, getDealers} from './api';
import {Button, Form, Row, Col, Card, Spin} from 'antd';
import {FORM_OPTIONS} from '../constants';
import Return from '../common/Return';
import FormItem from 'antd/lib/form/FormItem';
import {conventEnumValueToString} from '../utils';
import {PERMISSION, hasPermissions} from './constants';
import {newOrUpdateOrderValidator} from './validator';
import {injectIntl, formatMessage} from './intl';
import WrappedSelect from '../common/WrappedSelect';
import DealerSelectPanel from '../common/DealerSelect/SelectEdit';
import WrappedInputNumber from '../common/WrappedInputNumber';
import {currency} from '../Enum';
import styles from './style.css';
import InputAmount from '../common/InputAmount';
import TextInput from 'Shared/components/TextInput';
const EMPTY_ARRAY = [];
export class NewPanel extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        validate: false,
        data: {}
    };

    componentDidMount() {
        if(this.props.id)
            this.getDetailInfo();
    }
    
    componentWillUnmount() {
        this.isunmount = true;
    }

    getDetailInfo = () => {
        const id = this.props.id;
        this.setState({loading: true});
        getDetail(id)
            .then(res => {
                if(res.ok)
                    this.setState({
                        loading: false,
                        data: res.data
                    });
                this.setState({
                    loading: false
                });
            });
    }

    handleFilterChange = (value, name) => {
        const data = Object.assign({}, this.state.data, {
            [name]: value
        });
        this.setState({
            data,
            hasOperat: true
        });
    }

    onClickReturnBtn = () => {
        this.props.onCancel();
    }
    onSelectDealer = (condition = {}) => {
        this.setState(state => {
            const newData = cloneDeep(state.data);
            return {
                hasOperat: true,
                data: {
                    ...newData,
                    dealerId: condition.id,
                    dealerCode: condition.code,
                    dealerName: condition.name,
                    currency: condition.currency
                }
            };
        });
    };
    onSubmit = () => {
        const isValid = newOrUpdateOrderValidator(this.state.data);
        if(!isValid) {
            this.setState({
                validate: true
            });
            return;
        }
        this.setState({
            loading: true,
        });
        this.props.onSubmit(this.state.data).then(() => {
            if(this.success)
                this.props.successReturn();
            if(!this.isunmount)
                this.setState({loading: false});
        });
    }

    render() {
        const {data, validate} = this.state;
        const validateDealer = !data.dealerId && validate ? 'error' : null;
        const validateCurrency = !data.currency && validate ? 'error' : null;
        const validateBrand = !data.brandId && validate ? 'error' : null;
        const validateYear = !data.year && validate ? 'error' : null;
        const validateAmount = !data.amount && validate ? 'error' : null;
        const {pagePermission, brands, id} = this.props;
        const submitable = hasPermissions(PERMISSION.add, pagePermission);
        const dealerInfo = data.dealerId ? {
            id: data.dealerId,
            code: data.dealerCode,
            name: data.dealerName,
        } : null;
        const queryCondition = {
            brandId: data.brandId
        };
        const dealerComp = data.brandId ? (<DealerSelectPanel
            allowClear={false}
            value={dealerInfo}
            getDealerSimple={getDealersQuickly}
            getDealers={getDealers}
            conditions={queryCondition}
            onSelect={this.onSelectDealer} />) : (<TextInput name="dealerId"
            value={''} disabled={true} placeholder={formatMessage({
                id: 'newPanel.dealerComp.placeholder',
                defaultMessage: '请先选择品牌'
            })} />);
        return (
            <div className={styles.detail}>
                <Spin spinning={this.state.loading}>
                    <div className="form-standard">
                        <Form>
                            <Card {...FORM_OPTIONS.col} title={formatMessage({
                                id: 'newPanel.card.title',
                                defaultMessage: '基本信息'
                            })}>
                                <Row>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem label={formatMessage({
                                            id: 'newPanel.text.code',
                                            defaultMessage: '编号'
                                        })}{...FORM_OPTIONS.item} required>
                                            {id ? data.code
                                                : <span className="value-font">{formatMessage({
                                                    id: 'newPanel.value.defalut',
                                                    defaultMessage: '尚未生成'
                                                })}</span>}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.form.brand',
                                                defaultMessage: '品牌'
                                            })}
                                            {...FORM_OPTIONS.item} validateStatus={validateBrand} required >
                                            {id ? `${data.brandCode}(${data.brandName})`
                                                : <WrappedSelect
                                                    allowClear
                                                    name="brandId"
                                                    value={data.brandId}
                                                    options={brands}
                                                    onChange={this.handleFilterChange}/>}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.form.dealerId',
                                                defaultMessage: '总代'
                                            })}
                                            {...FORM_OPTIONS.item} validateStatus={validateDealer} required>
                                            {id ? `${data.dealerCode}(${data.dealerName})`
                                                : dealerComp}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.form.currency',
                                                defaultMessage: '币种'
                                            })} {...FORM_OPTIONS.item} validateStatus={validateCurrency} required>
                                            {conventEnumValueToString(currency, data.currency)}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'queryPanel.form.year',
                                                defaultMessage: '年份'
                                            })}
                                            {...FORM_OPTIONS.item} validateStatus={validateYear} required>
                                            {id ? data.year
                                                : <WrappedInputNumber
                                                    min={0}
                                                    precision={0}
                                                    name="year"
                                                    value={data.year}
                                                    onBlur={this.handleFilterChange} />}
                                        </FormItem>
                                    </Col>
                                    <Col {...FORM_OPTIONS.col}>
                                        <FormItem
                                            label={formatMessage({
                                                id: 'newPanel.form.amount',
                                                defaultMessage: '总预算'
                                            })} {...FORM_OPTIONS.item} validateStatus={validateAmount} required>
                                            <InputAmount
                                                name="amount"
                                                value={data.amount}
                                                onChange={this.handleFilterChange}/>
                                        </FormItem>
                                    </Col>
                                </Row>
                            </Card>
                            <Card type="inner">
                                <Row>
                                    <Col disabled={!submitable} className="col-align-right">
                                        <Button key="submit" loading={this.state.loading}
                                            onClick={this.onSubmit} type="primary">{formatMessage({
                                                id: 'newPanel.btn.submit',
                                                defaultMessage: '保存'
                                            })}</Button>
                                    </Col>
                                </Row>
                            </Card>
                        </Form>
                    </div>
                    
                </Spin>
                <div className="page-toolbar">
                    <Return
                        onConfirm={this.onClickReturnBtn}
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat} />
                </div> 
            </div>
        );
    }
}

NewPanel.propTypes = {
    onCancel: PropTypes.func.isRequired,
    onSubmit: PropTypes.func.isRequired,
    history: PropTypes.object,
    pagePermission: PropTypes.array,
};
import {connect} from 'react-redux';
import {
    onSubmit,
    tableSearch,
} from './actions';
import {selectorFactory} from 'Shared/utils/immutableToJsSelectorFactory';
import {createSelector} from 'reselect';
const getPagePermission = selectorFactory(['page', 'domainData', 'permissions', 'data']);
const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'initData', 'brands']),
    data => {
        const brands = data.toJS();
        return brands
            ? brands.map(item => ({
                value: item.id,
                text: `(${item.code})${item.name}`
            }))
            : EMPTY_ARRAY;
    }
);

const mapStateToProps = state => ({
    pagePermission: getPagePermission(state),
    brands: getBrands(state),
});

const mapDispatchToProps = (dispatch, props) => {
    const ownProps = {
        onSubmit: data => dispatch(onSubmit(data)).then(result => {
            if(result.success) {
                dispatch(tableSearch());
                props.history.push(routes.query.url());
            }
        }),
        onCancel: () => props.history.push(routes.query.url())
    };
    return ownProps;
};

export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(NewPanel));
